﻿(function ($) {


    $.extend({

        ie6: function () {
            return $.browser.msie && $.browser.version.substring(0, 1) === '6';
        },
        undefined: function () {
            for (var i = 0; i < arguments.length; i++)
                if (typeof arguments[i] != 'undefined') return false;
            return true;
        },

        viewport: function () {
            var d = document.documentElement, b = document.body, w = window;
            return jQuery.extend(
                    jQuery.browser.msie ?
                        { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop} :
                        { left: w.pageXOffset, top: w.pageYOffset },
                    !$.undefined(w.innerWidth) ?
                        { width: w.innerWidth, height: w.innerHeight} :
                        (!$.undefined(d) && !$.undefined(d.clientWidth) && d.clientWidth != 0 ?
                            { width: d.clientWidth, height: d.clientHeight} :
                            { width: b.clientWidth, height: b.clientHeight }));
        },

        getDocHeight: function () {

            var b = document.body,
                e = document.documentElement,
                w = 0,
                h = 0;
            if (e) {
                //w = Math.max(w, e.scrollWidth, e.offsetWidth);
                h = Math.max(h, e.scrollHeight, e.offsetHeight);
            }
            if (b) {
                // w = Math.max(w, b.scrollWidth, b.offsetWidth);
                h = Math.max(h, b.scrollHeight, b.offsetHeight);
                if (window.innerWidth) {
                    //  w = Math.max(w, window.innerWidth);
                    h = Math.max(h, window.innerHeight);
                }
            }
            return h; // [w, h];

        },

        toArguments: function (array) {
            return $.map(array, function (a) {
                return $(a).val();
            });
        },
        queryString: function (key) {
            key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regex = new RegExp("[\\?&]" + key + "=([^&#]*)", 'ig');
            var qs = regex.exec(window.location.href);
            if (qs == null)
                return '';
            else
                return qs[1];

        },




        dateFormat: function (date, f) {

            var d = date;

            return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
                    function ($1) {
                        switch ($1.toLowerCase()) {
                            case 'yyyy': return d.getFullYear();
                            case 'mmmm': return gsMonthNames[d.getMonth()];
                            case 'mmm': return gsMonthNames[d.getMonth()].substr(0, 3);
                            case 'mm': return ((d.getMonth() + 1) > 10) ? (d.getMonth() + 1) : "0" + (d.getMonth() + 1);
                            case 'dddd': return gsDayNames[d.getDay()];
                            case 'ddd': return gsDayNames[d.getDay()].substr(0, 3);
                            case 'dd': return (d.getDate() > 10) ? d.getDate() : "0" + d.getDate();
                            case 'hh':
                                var h;
                                return ((h = d.getHours() % 12) ? h : 12);
                            case 'nn': return d.getMinutes();
                            case 'ss': return d.getSeconds();
                            case 'a/p': return d.getHours() < 12 ? 'a' : 'p';
                        }
                        return d.getUTCDate();
                    });

        },


        bookmark: function (title, url) {
            if (window.sidebar) { // Mozilla Firefox Bookmark
                window.sidebar.addPanel(title, url, "");
            } else if (window.external) { // IE Favorite
                window.external.AddFavorite(url, title);
            } else if (window.opera) { // Opera 7+
                return false; // do nothing
            } else {
                alert('Unfortunately, this browser does not support the requested action, please bookmark this page manually.');

            }
            return false;
        },

        showDialog: function (url, opts) {

            var winH = $(window).height();
            var winW = $(window).width();
            var w = opts && opts.width > 0 ? opts.width : winW * 0.8;
            var h = opts && opts.height > 0 ? opts.height : winH * 0.8;
            var winX = (winW - w) * .5;
            var winY = (winH - h) * .5;
            window.showModalDialog(url, opts, 'dialogWidth:' + w + ',dialogHeight:' + h + ',center:1,modal:1;dialogTop:' + winY + ';dialogLeft:' + winX);
        },



        isEnter: function (event) {

            return ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13));

        },

        isImage: function (fileUrl) {
            var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png|jpeg|bmp)", 'i');
            //var _reg = new RegExp("^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$", 'i');                
            if (_reg.test(fileUrl))
                return true;
            else
                return false;
        },

        isFlash: function (fileUrl) {
            var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:swf)", 'i');
            //var _reg = new RegExp('^[a-zA-Z0-9-_\.]+\.(swf)$', 'i');
            if (_reg.test(fileUrl))
                return true;
            else
                return false;
        },

        isYoutube: function (fileUrl) {
            //var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:swf)", 'i');
            var _reg = new RegExp('http://(?:\S+?youtube\S+)', 'i');
            if (_reg.test(fileUrl))
                return true;
            else
                return false;
        },
        truncate: function (value, arg) {
            var valueArr = value.split(' ');
            if (arg < valueArr.length) {
                value = valueArr.slice(0, arg).join(' ');
            }
            return value;
        },


        /* -----------------------Html Encode-Decode---------------------------*/

        Html: {
            encode: function (html) {
                html = html.replace(/&quot;/g, '&quotx;');
                html = html.replace(/"/g, '&quot;');
                html = html.replace(/&amp;/g, '&ampx;');
                html = html.replace(/&/g, '&amp;');
                html = html.replace(/&lt;/g, '&ltx;');
                html = html.replace(/</g, '&lt;');
                html = html.replace(/&gt;/g, '&gtx;');
                html = html.replace(/>/g, '&gt;');
                return html;
            },
            democde: function (html) {
                html = html.replace(/&gt;/g, '>');
                html = html.replace(/&gtx;/g, '&gt;');
                html = html.replace(/&lt;/g, '<');
                html = html.replace(/&ltx;/g, '&lt;');
                html = html.replace(/&amp;/g, '&');
                html = html.replace(/&ampx;/g, '&amp;');
                html = html.replace(/&quot;/g, '"');
                html = html.replace(/&quotx;/g, '&quot;');
                return html;
            }
        },



        String: {
            trim: function () {
                return this.replace(/^\s+|\s+$/g, '');
            },

            //if( $.StringEx.isNullOrEmpty('') ) alert('Empty string');
            isNullOrEmpty: function (value) {
                if (value) {
                    if (typeof (value) == 'string') {
                        if (value.length > 0)
                            return false;
                    }
                    if (value != null)
                        return false;
                }
                return true;

            },

            replace: function (source, oldVal, newVal) {
                var result = source;
                result = result.replace(new RegExp('\\' + oldVal + '\\', 'g'), newVal);
                return result;
            },

            format: function (format) {
                var result = format;
                for (var i = 1; i < arguments.length; i++) {
                    result = result.replace(new RegExp('\\{' + (i - 1) + '\\}', 'g'), arguments[i]);
                }
                return result;
            },
            startsWith: function (prefix, ignoreCase) {
                if (!prefix) return false;
                if (prefix.length > this.length) return false;
                if (ignoreCase) {
                    if (ignoreCase == true) {
                        return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
                    }
                }
                return (this.substr(0, prefix.length) === prefix);
            },
            endsWith: function (suffix, ignoreCase) {
                if (!suffix) return false;
                if (suffix.length > this.length) return false;
                if (ignoreCase) {
                    if (ignoreCase == true) {
                        return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
                    }
                }
                return (this.substr(this.length - suffix.length) === suffix);
            }
        },


        Ajax: {
            defaults: {
                target: '#_ajaxContainer',
                tinymce: null,
                loading: true,
                callback: function (d) { $.Ajax.success(d); },
                hashPwd: null

            },

            submit: function (f, options) {

                var _f = (typeof f == 'object') ? f : $('#' + f);

                var _s = $.extend({}, this.defaults, options || {}, $.metadata ? _f.metadata() : $.meta ? _f.data() : {});

                if (_s.tinymce && window.tinymce) {
                    window.tinyMCE.triggerSave();
                };

                var _validate = _f.validate({ meta: 'validate', invalidHandler: function () { $(this).find(":input.error:first").focus(); } });

                if (_validate.form()) {

                    if (_s.loading && $.Loading) {
                        $.Loading.show();
                    };

                    if (_s.hashPwd && $.Hash) {
                        _f.find(":password").each(function () {
                            var _v = $(this).val();
                            $(this).val($.Hash.sha256(_v));
                        });
                    };

                    _f.find(":checkbox").each(function () {
                        $(this).val($(this).is(":checked"));
                    });


                    if (_f.attr("fvalid") != "1") {
                        _f.attr("fvalid", "1");
                        _f.append('<input type="hidden" value="1" name="fvalid" /><input type="hidden" value="1" name="ajax" />');

                    };

                    $.post(
                    _f.attr("action"),
                    _f.serialize(),
                    function (response) {
                        var d = (typeof response) == 'string' ? eval('(' + response + ')') : response;
                        if (_s.callback) {
                            if ($.isFunction(_s.callback))
                                _s.callback.call(this, d);
                            else
                                eval(_s.callback);
                        }
                    }).
                    error(function (xhr, ajaxOptions, thrownError) {
                        if ($.KoolBox) {
                            $.KoolBox.alert('Error:' + xhr.status + '<br />' + thrownError);
                        }
                        else {

                            alert('Error:' + xhr.status + '\n' + thrownError);
                        }

                    }).complete(function () {

                        if (_s.hashPwd && $.Hash) {
                            _f.find("input:password").val('');
                        }

                        if (_s.loading && $.Loading) {
                            $.Loading.hide();
                        }

                    });

                } // end validate

            },

            load: function (url, options) {

                //var url = (typeof href == 'object') ? href.attr('href') : href;

                var s = $.extend({}, this.defaults, options || {});

                if (s.target) {
                    if (s.loadding && $.Loading) {
                        $.Loading.show();
                    }
                    $(s.target).load(url, function () {
                        if (s.loadding && $.Loading) {
                            $.Loading.hide();
                        }
                        if (s.tinymce && window.tinymce && $.Editor) {
                            $.Editor.init();
                        }

                        if (s.recaptcha && $.fn.recaptcha) {
                            $('.recaptcha').recaptcha();
                        }


                        if ($.fn.scrollTo) {
                            $(s.target).scrollTo(0, 300);
                        }

                    });
                }
            },
            success: function (d) {
                if (d.Reload) {
                    window.location.reload();
                    return;

                }

                if (!$.String.isNullOrEmpty(d.Text)) {

                    if (d.Alert) {

                        if ($.KoolBox) {

                            $.KoolBox.alert(d.Text);
                        }
                        else {
                            alert(d.Text);
                        }

                    }
                    else {

                        $(d.TargetId).html(d.Text);

                        if (d.Inbox) {
                            $(d.TargetId).parent().fadeIn();
                        }

                        $(d.TargetId).scrollTo(0, 300);
                    }
                }
                
                if (!$.String.isNullOrEmpty(d.ReturnUrl))
                    window.location = d.ReturnUrl;

                if (d.Callback) {
                    eval(d.Callback);
                }

            }
        },

        Overlay: {
            defaults: {
                bg: '#333333',
                opacity: 0.3,
                width: '100%',
                showDuration: 500,
                hideDuration: 300
            },
            options: {},
            getId: function () {
                return $($.String.format("#overlay_{0}", this.Id));
            },
            create: function (s) {

                this.options = s = $.extend({}, this.defaults, s || {});

                this.Id = new Date().getTime();
                var o = $($.String.format('<div id="overlay_{0}"></div>', this.Id));
                $('body').append(o);
                o.css({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    background: s.bg,
                    opacity: s.opacity,
                    zIndex: s.zIndex,
                    width: s.width,
                    height: $(document).outerHeight()
                }).hide().fadeIn(s.showDuration);

                //this.created = true;
            },
            show: function (s) {

                if (this.Id) {
                    this.getId().fadeIn(this.options.showDuration);
                }
                else {
                    this.create(s);
                }

            },
            hide: function () {
                this.getId().fadeOut(this.options.hideDuration);
            }
        },

        Loading: {
            visibled: false,
            defaults: {
                theme: '',
                modal: 1,
                zIndex: 99999,
                position: ['center', 'center'], // ['center','top','right','bottom','left']
                margin: 10
            },

            getId: function () {
                return $($.String.format("#loading_{0}", this.Id));
            },
            showPosition: function () {

                if (!this.visibled) return;

                var s = this.options;
                var e = this.getId();
                var v = $.viewport();
                var h = e.outerHeight();
                var w = e.outerWidth();

                var t = 0, l = 0;

                switch (s.position[0]) {

                    default:
                    case 'center':
                        l = v.left + ((v.width - w) / 2);
                        t = v.top + ((v.height - h) / 2);
                        break;
                    case 'top-left':
                        t = v.top + s.margin;
                        l = v.left + s.margin;
                        break;
                    case 'top-right':
                        t = v.top + s.margin;
                        l = v.left + v.width - w - s.margin * 2;
                        break;

                    case 'bottom-left':
                        t = v.top + v.height - h - s.margin;
                        l = v.left + s.margin;
                        break;
                    case 'bottom-right':
                        t = v.top + v.height - h - s.margin;
                        l = v.left + v.width - w - s.margin * 2;
                        break;

                }
                if (this.animating) {
                    this.animating.stop();
                }
                e.show();
                this.animating = e.animate({ top: t, left: l }, {
                    duration: this.options.showDuration,
                    queue: false
                });

            },
            setEvents: function () {
                $(window).bind('resize scroll', $.proxy(function () {

                    this.showPosition();

                }, this));

                $(window).bind('keydown', $.proxy(function (e) {
                    if (e.keyCode == 27) {
                        this.hide();
                        e.preventDefault();
                    }
                }, this));
            },
            create: function (s) {

                this.Id = new Date().getTime();

                var e = $($.String.format('<div id="loading_{0}" class="loading {1}"></div>', this.Id, s.theme));

                $('body').append(e);
                e.css({ position: 'absolute', zIndex: s.zIndex });

                this.showPosition();
                this.setEvents();

                //this.created = true;
            },

            show: function (s, o) {


                this.options = s = $.extend({}, this.defaults, s || {});
                if (this.options.modal) {
                    o = $.extend(true, { zIndex: s.zIndex - 1 }, o || {});
                    $.Overlay.show(o);
                }
                this.visibled = true;
                if (this.Id) {
                    this.showPosition();
                }
                else {

                    this.create(s);
                }

            },
            hide: function () {
                if (this.options.modal) {
                    $.Overlay.hide();
                }
                this.getId().hide();
                this.visibled = false;
            }
        },

        /*-------------Environment----------------*/
        Environment: {
            idleTime: 0,
            standby: false,
            options: {},
            defaults: {
                zIndex: 999999,
                text: 'Chế độ tiết kiệm năng lượng<br /><span>Di chuyển chuột để trở lại trang hiện tại.</span>'
            },
            getId: function () {
                return $($.String.format('#energy_{0}', this.Id));
            },

            showPosition: function () {

                var s = this.options;
                var e = this.getId();
                var v = $.viewport();
                var h = e.outerHeight();
                var w = e.outerWidth();
                var t = 0, l = 0;
                l = v.left + ((v.width - w) / 2);
                t = v.top + ((v.height - h) / 2);

                e.css({ position: 'absolute', zIndex: s.zIndex, top: t, left: l }).show();

            },
            create: function () {

                this.Id = new Date().getTime();
                var e = $($.String.format('<div id="energy_{0}" class="energysaving"></div>', this.Id));
                $('body').append(e);
                e.html(this.options.text);

                this.showPosition();

            },
            setStandBy: function () {
                if (!this.standby) {

                    $.Overlay.show({ opacity: 1.0, bg: '#000', zIndex: this.options.zIndex - 1 });

                    if (this.Id) {
                        this.showPosition();
                    }
                    else {
                        this.create();
                    }
                    this.standby = true;
                }
            },


            stopStandBy: function () {
                if (this.standby) {
                    $.Overlay.hide();
                    this.getId().hide();
                    this.standby = false;
                };

                this.idleTime = 0;
            },
            checkActivity: function () {

                this.idleTime += 10;
                if (this.idleTime > 60) {
                    this.setStandBy();
                }


            },

            init: function (o) {

                this.options = $.extend({}, this.defaults, o | {});

                $(document).bind('click keypress mousemove', $.proxy(function () {
                    this.stopStandBy();
                }, this));

                setInterval($.proxy(function () {
                    this.checkActivity();
                }, this), 1000);


            }

        }

    });


})(jQuery);
    
